package com.choudou5.solr.web.handler.sys;

import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.api.ApiConfig;
import com.choudou5.solr.api.SearchApi;
import com.choudou5.solr.bean.common.SolrQueryParam;
import com.choudou5.solr.core.util.SolrHelper;
import com.choudou5.solr.framework.constants.DictConsts;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.service.DicExtWordsService;
import com.choudou5.solr.service.SearchHiService;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.util.DateUtil;
import com.choudou5.solr.util.ReportUtil;
import com.choudou5.solr.util.SolrJUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.bean.DateRange;
import com.choudou5.solr.utils.SolrQueryBuilder;
import com.choudou5.solr.utils.SysDictUtil;
import com.choudou5.solr.web.handler.BaseHandler;
import org.apache.solr.common.params.FacetParams;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Name：首页 处理器
 * @Author：choudou5
 * @Date：2018-07-15
 */
public class IndexHandler extends BaseHandler {

    private static SearchApi searchApi = SearchApi.getInstance();
    private static SearchHiService searchHiService = ServiceHelper.singleton(SearchHiService.class);
    private static DicExtWordsService extWordsService = ServiceHelper.singleton(DicExtWordsService.class);


    @Override
    public void execute(String method, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("IndexHandler method:{}", method);
        switch (method){
            case "statNum":
                statNum(req, resp);
                break;
            case "statReport":
                statReport(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }

    @ReqMapping(desc = "数量统计", method = ReqMethod.POST)
    private void statNum(HttpServletRequest req, HttpServletResponse resp){
        Date yesterday = DateUtil.yesterday();
        String yesterdayBegin = DateUtil.beginOfDay(yesterday).toString();
        String yesterdayEnd = DateUtil.endOfDay(yesterday).toString();
        Map map = new HashMap<>();
        //新增问答数据
        SolrQueryParam queryParam = new SolrQueryParam(ApiConfig.API_QA, SolrJUtil.QUERY_ALL, SolrJUtil.QUERY_ALL);
        map.put("qaTotal", searchApi.count(queryParam));
        SolrQueryBuilder.appendFilterQuery(queryParam, "createTime", "[" + DateUtil.toSolrDate(DateUtil.beginOfDay(yesterday)) + " TO "+ DateUtil.toSolrDate(DateUtil.endOfDay(yesterday)) + "]");
        map.put("qaNewTotal", searchApi.count(queryParam));
        //搜索历史
        map.put("searchNewTotal", searchHiService.count("create_time BETWEEN '"+yesterdayBegin+"' AND '"+yesterdayEnd+"';"));
        map.put("searchTotal", searchHiService.countAll());
        //词库
        map.put("dictWordNewTotal", searchHiService.count("create_time BETWEEN '"+yesterdayBegin+"' AND '"+yesterdayEnd+"';"));
        map.put("dictWordTotal", extWordsService.countAll());
        PageJumpUtil.writeJsonObjOk(map, resp);
    }

    @ReqMapping(desc = "报表统计", method = ReqMethod.POST)
    private void statReport(HttpServletRequest req, HttpServletResponse resp){
        String startRunTime = SysDictUtil.getOneValueByType(DictConsts.SYS_START_RUN_TIME);
        DateRange dateRange = DateUtil.getStatRangeDate(startRunTime);
        List<String> dateListX = dateRange.toDateStrList(true);
        Map map = new HashMap<>();
        map.put("qaCountReportLabels", dateListX);
        map.put("searchCountReportLabels", dateListX);
        map.put("dictWordCountReportLabels", dateListX);

        //问答数据
        SolrQueryParam queryParam = new SolrQueryParam(ApiConfig.API_QA, SolrJUtil.QUERY_ALL, SolrJUtil.QUERY_ALL);
        queryParam.setFacet(true).set(FacetParams.FACET_DATE, "createTime")
                .set(FacetParams.FACET_DATE_START, DateUtil.toSolrDate(dateRange.getStartDate()))
                .set(FacetParams.FACET_DATE_END, DateUtil.toSolrDate(dateRange.getEndDate()))
                .set(FacetParams.FACET_DATE_GAP, "+" + dateRange.getDiffDateType());
//        &facet=true&facet.date=createTime&facet.date.start=2018-07-28T11:09:42Z&facet.date.end=2018-10-23T16:54:47Z&facet.date.gap=%2B5DAY
        List<String> qaCountStat = searchApi.getFacetDateList("createTime", queryParam, dateRange.getFormat());
        map.put("qaCountReportDatas", ReportUtil.getDataListByDateList(dateListX, qaCountStat));

        String column = "CONCAT(DATE_FORMAT(create_time, '"+dateRange.getSqlFormat()+"'), '=', COUNT(1)) statInfo";
        String appendStatement = " WHERE create_time >= '"+dateRange.getStartDateStr()+"' GROUP BY DATE_FORMAT(create_time, '"+dateRange.getSqlFormat()+"');";
        //搜索次数数据
        List<String> searchCountStat = searchHiService.findOneColumnListByAppendStatement(String.class, column, appendStatement);
        map.put("searchCountReportDatas", ReportUtil.getDataListByDateList(dateListX, searchCountStat));
        //词库数据
        List<String> dictWordCountStat = extWordsService.findOneColumnListByAppendStatement(String.class, column, appendStatement);
        map.put("dictWordCountReportDatas", ReportUtil.getDataListByDateList(dateListX, dictWordCountStat));
        PageJumpUtil.writeJsonObjOk(map, resp);
    }
}
